package com.baohua.controller;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baohua.exception.BaohuaSystemException;
import com.baohua.model.Menu;
import com.baohua.service.MenuService;

@Controller
@RequestMapping("/menu")
public class MenuController {
	
  /**
   * 异步加载所有菜单列表
   * @param request
   * @return
   */
	@RequestMapping("/list")
	public @ResponseBody List<Menu> queryMenu(){
	    List<Menu> list = menuService.queryMenu();
        return list;	    
	}
	
	/**
	 * 跳转菜单主页面
	 * @return
	 */
	@RequestMapping("/index")
	public String index(){
		return "menu";
	}
	
	/**
	 * 增加菜单节点
	 * @param request
	 * @return
	 */
	@RequestMapping(value="add", method=RequestMethod.POST)
	public String addMenu(Menu menu, Model model) {
		try {
			menuService.addMenu(menu);
		} catch (BaohuaSystemException e) {
			logger.info(e.getMessage());
			//将错误抛出到后台
			model.addAttribute("errorMessage", e.getMessage());
    		return "forward:/system/error";
		}
		
		return "redirect:/menu/index";
	}
	
	/**
	 * 修改节点
	 * @param menu
	 * @param model
	 * @return
	 */
	@RequestMapping(value="update", method=RequestMethod.POST)
	public String updateMenu(Menu menu, Model model) {
		try {
			menuService.updateMenu(menu);
		} catch (BaohuaSystemException e) {
			logger.info(e.getMessage());
			//将错误抛出到后台
			model.addAttribute("errorMessage", e.getMessage());
    		return "forward:/system/error";
		}
		
		return "redirect:/menu/index";
	}
	/**
	 * 删除节点
	 * @param menuNO
	 * @param model
	 * @return
	 */
	@RequestMapping(value="delete/{menuNO}", method=RequestMethod.GET)
	public String deleteMenu(@PathVariable String menuNO, Model model) {
		try {
			menuService.delMenu(menuNO);
		} catch (BaohuaSystemException e) {
			logger.info(e.getMessage());
			//将错误抛出到后台
			model.addAttribute("errorMessage", e.getMessage());
    		return "forward:/system/error";
		}
		
		return "redirect:/menu/index";
	}
	
	
	private static Logger logger = LoggerFactory.getLogger(MenuController.class);
	private MenuService menuService;
	
	public MenuService getMenuService() {
		return menuService;
	}

	@Resource(name="menuService")
	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	
}
